from typing import Any, List
from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.orm import Session

from app.api import deps
from app.schemas import carrier
from app.database.models.erp import Carrier
from app.database.models.base import User

router = APIRouter()

@router.get("/", response_model=List[carrier.Carrier])
def list_carriers(
    db: Session = Depends(deps.get_db),
    skip: int = 0,
    limit: int = 100,
    current_user: User = Depends(deps.get_current_active_user)
) -> Any:
    """获取承运人列表"""
    carriers = db.query(Carrier).offset(skip).limit(limit).all()
    return carriers

@router.post("/", response_model=carrier.Carrier)
def create_carrier(
    *,
    db: Session = Depends(deps.get_db),
    carrier_in: carrier.CarrierCreate,
    current_user: User = Depends(deps.get_current_active_user)
) -> Any:
    """创建新承运人"""
    if current_user.role != "admin":
        raise HTTPException(status_code=403, detail="Not enough permissions")
    
    # 检查代码是否已存在
    if db.query(Carrier).filter(Carrier.Code == carrier_in.Code).first():
        raise HTTPException(
            status_code=400,
            detail="Carrier code already registered"
        )
    
    carrier = Carrier(**carrier_in.dict())
    db.add(carrier)
    db.commit()
    db.refresh(carrier)
    return carrier

@router.get("/{carrier_id}", response_model=carrier.Carrier)
def get_carrier(
    carrier_id: int,
    db: Session = Depends(deps.get_db),
    current_user: User = Depends(deps.get_current_active_user)
) -> Any:
    """获取特定承运人信息"""
    carrier = db.query(Carrier).filter(Carrier.ID == carrier_id).first()
    if not carrier:
        raise HTTPException(status_code=404, detail="Carrier not found")
    return carrier

@router.put("/{carrier_id}", response_model=carrier.Carrier)
def update_carrier(
    *,
    db: Session = Depends(deps.get_db),
    carrier_id: int,
    carrier_in: carrier.CarrierUpdate,
    current_user: User = Depends(deps.get_current_active_user)
) -> Any:
    """更新承运人信息"""
    if current_user.role != "admin":
        raise HTTPException(status_code=403, detail="Not enough permissions")
    
    carrier = db.query(Carrier).filter(Carrier.ID == carrier_id).first()
    if not carrier:
        raise HTTPException(status_code=404, detail="Carrier not found")
    
    for field, value in carrier_in.dict(exclude_unset=True).items():
        setattr(carrier, field, value)
    
    db.add(carrier)
    db.commit()
    db.refresh(carrier)
    return carrier

@router.delete("/{carrier_id}")
def delete_carrier(
    *,
    db: Session = Depends(deps.get_db),
    carrier_id: int,
    current_user: User = Depends(deps.get_current_active_user)
) -> Any:
    """删除承运人"""
    if current_user.role != "admin":
        raise HTTPException(status_code=403, detail="Not enough permissions")
    
    carrier = db.query(Carrier).filter(Carrier.ID == carrier_id).first()
    if not carrier:
        raise HTTPException(status_code=404, detail="Carrier not found")
    
    db.delete(carrier)
    db.commit()
    return {"ok": True} 